<template>
  <div class="app-container">

    <!-- 表头 查询与新增 -->
    <el-row>
      <el-col :span="24">
        <div class="filter-container">
          <el-input v-model="listQuery.query" placeholder="用户昵称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
          <el-input v-model="listQuery.userTel" placeholder="用户电话" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>

          <el-select
            v-model="listQuery.validFlag"
            placeholder="有效标志"
            clearable
            class="filter-item"
            style="width: 150px"
            @change="handleFilter">
            <el-option v-for="(value, key) in statusOptions" :key="key" :label="value+'('+key+')'" :value="key"/>
          </el-select>

          <el-select
            v-model="listQuery.followType"
            placeholder="关注注册标志"
            clearable
            class="filter-item"
            style="width: 150px"
            @change="handleFilter">
            <el-option v-for="(value, key) in followOptions" :key="key" :label="value" :value="key"/>
          </el-select>

          <el-date-picker
            class="filter-item"
            v-model="buyTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
          <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-circle-plus-outline" @click="handleCreate">新增</el-button>
          <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-circle-plus-outline"
                     @click="exportReport">导出用户信息
          </el-button>
        </div>
      </el-col>
    </el-row>

    <!-- 表格list -->
    <el-row>
      <el-col :span="24" :gutter="24">
        <el-table
          v-loading="listLoading"
          :key="tableKey"
          :data="list"
          :height="tableHeight"
          element-loading-text="Loading"
          border
          fit
          style="width: 100%;"
          highlight-current-row>
          <el-table-column align="center" label="序号" width="80">
            <template slot-scope="scope">
              {{ scope.$index }}
            </template>
          </el-table-column>
          <el-table-column label="用户昵称" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.nickName }}
            </template>
          </el-table-column>
         <!-- <el-table-column label="用户头像" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              <img :src="scope.row.headImg"/>
            </template>
          </el-table-column>-->
          <el-table-column label="等级名称" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.userRankName }}
            </template>
          </el-table-column>
          <el-table-column label="当前积分" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.userPoints }}
            </template>
          </el-table-column>
          <!--<el-table-column label="用户级别" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.userLevel }}
            </template>
          </el-table-column>-->
          <el-table-column label="用户电话" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.userTel }}
            </template>
          </el-table-column>
          <!--<el-table-column label="支付账户" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.payNo }}
            </template>
          </el-table-column>-->
          <el-table-column label="账户余额" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.moneyBalance }}
            </template>
          </el-table-column>
          <el-table-column label="推荐者" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.parentName }}
            </template>
          </el-table-column>
          <el-table-column label="是否关注" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.followFlag }}
            </template>
          </el-table-column>
          <el-table-column label="关注时间" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.followTime | timeFilter }}
            </template>
          </el-table-column>
          <el-table-column label="创建时间" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.createdTime | timeFilter }}
            </template>
          </el-table-column>
          <el-table-column label="修改时间" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.modifiedTime | timeFilter }}
            </template>
          </el-table-column>
          <el-table-column label="最后登录时间" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.lastLoginTime | timeFilter }}
            </template>
          </el-table-column>
          <!--<el-table-column class-name="status-col" label="有效标志" style="width: 10%" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.validFlag | statusFilter">{{ scope.row.validFlag | validFilter }}</el-tag>
            </template>
          </el-table-column>-->
          <el-table-column label="用户姓名" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.userName }}
            </template>
          </el-table-column>
          <el-table-column label="用户性别" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.userSex }}
            </template>
          </el-table-column>
          <el-table-column label="出生日期" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.birthDay | timeFilter }}
            </template>
          </el-table-column>
          <!--<el-table-column label="默认卡类型" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.defaultCard }}
            </template>
          </el-table-column>-->
          <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="success" @click="downQrUrl(scope.row)">
                二维码生成
              </el-button>
              <!--<el-button size="mini" type="primary" @click="handleUpdate(scope.row)">-->
              <!--编辑-->
              <!--</el-button>-->
              <!--<el-button size="mini" type="danger" @click="handleDelete(scope.row)">-->
              <!--删除-->
              <!--</el-button>-->
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="showPoint(scope.row)">
                积分流水
              </el-button>
              <!--<el-button size="mini" type="primary" @click="handleUpdate(scope.row)">-->
              <!--编辑-->
              <!--</el-button>-->
              <!--<el-button size="mini" type="danger" @click="handleDelete(scope.row)">-->
              <!--删除-->
              <!--</el-button>-->
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="listQuery.pageNum"
          :limit.sync="listQuery.pageSize"
          layout="total, sizes, prev, pager, next"
          style="float:right;"
          @pagination="fetchData"/>
      </el-col>
    </el-row>

    <!-- 编辑弹窗 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="100px"
        style="">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户昵称" label-width="105px" prop="nickName">
              <el-input v-model="temp.nickName"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户头像" label-width="105px" prop="headImg">
              <el-input v-model="temp.headImg"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="等级名称" label-width="105px" prop="userRankName">
              <el-input v-model="temp.userRankName"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当前积分" label-width="105px" prop="userPoints">
              <el-input v-model="temp.userPoints"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户级别" label-width="105px" prop="userLevel">
              <el-input v-model="temp.userLevel"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户电话" label-width="105px" prop="userTel">
              <el-input v-model="temp.userTel"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="支付账户" label-width="105px" prop="payNo">
              <el-input v-model="temp.payNo"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="账户余额" label-width="105px" prop="moneyBalance">
              <el-input v-model="temp.moneyBalance"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否关注" label-width="105px" prop="followFlag">
              <el-input v-model="temp.followFlag"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关注时间" label-width="105px" prop="followTime">
              <el-input v-model="temp.followTime"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户姓名" label-width="105px" prop="userName">
              <el-input v-model="temp.userName"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户性别" label-width="105px" prop="userSex">
              <el-input v-model="temp.userSex"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出生日期" label-width="105px" prop="birthDay">
              <el-input v-model="temp.birthDay"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="有效标志" label-width="105px">
              <el-switch
                v-model="validSwitch"
                active-color="#13ce66"
                inactive-color="#ff4949"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确认</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="dialogPointFormVisible"
      title="积分流水">
      <el-row>
        <el-col :span="24" :gutter="24">
          <el-table
            :data="pointListData"
            element-loading-text="Loading"
            border
            fit
            :height="tableHeight"
            style="width: 100%;"
            highlight-current-row>
            <el-table-column align="center" label="序号" width="80">
              <template slot-scope="scope">
                {{ scope.$index }}
              </template>
            </el-table-column>
            <el-table-column label="获取积分" show-overflow-tooltip style="width: 10%" align="center">
              <template slot-scope="scope">
                {{ scope.row.points }}
              </template>
            </el-table-column>
            <el-table-column label="获取方式" show-overflow-tooltip style="width: 10%" align="center">
              <template slot-scope="scope">
                {{ scope.row.way }}
              </template>
            </el-table-column>
            <el-table-column label="描述信息" show-overflow-tooltip style="width: 10%" align="center">
              <template slot-scope="scope">
                {{ scope.row.desc1 }}
              </template>
            </el-table-column>
            <el-table-column label="创建时间" show-overflow-tooltip style="width: 10%" align="center">
              <template slot-scope="scope">
                {{ scope.row.createTime | timeFilter }}
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="pointListTotal>0" :total="pointListTotal"
                      :page.sync="pointListQuery.pageNum"
                      :limit.sync="pointListQuery.pageSize"
                      layout="total, sizes, prev, pager, next"
                      style="float:right;"
                      @pagination="getUserPoint"/>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogPointFormVisible = false">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import SxUserInfoApi from '@/api/manage/SxUserInfoApi'
  import SxUserScoreRecordApi from '@/api/manage/SxUserScoreRecordApi'
  import waves from '@/directive/waves' // Waves directive
  import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
  export default {
    directives: { waves },
    components: { Pagination },
    filters: {
      statusFilter(status) {
        const statusMap = {
          1: 'success',
          2: 'gray',
          0: 'danger'
        }
        return statusMap[status]
      },
      validFilter(status) {
        const statusMap = {
          1: '有效',
          0: '作废'
        }
        return statusMap[status]
      },
      timeFilter(time) {
        if (time) {
          return new Date(time).Format('yyyy-MM-dd hh:mm:ss')
        } else {
          return ''
        }
      }
    },
    data() {
      return {
        tableKey: 0, // 表格key值
        list: null, // 表格对象
        listLoading: true, // 表格加载框
        total: 0, // 分页总数
        buyTime: '',
        tableHeight: window.innerHeight - 220, // 表格高度
        listQuery: { // 表格查询对象
          pageNum: 1,
          pageSize: 10,
          query: '',
          validFlag: undefined,
          followType: '',
          userTel: '',
          userId: ''
        },
        temp: {}, // 编辑框临时变量
        exportUrl: process.env.BASE_API + 'sxUserInfo/exportExcel', //用户信息导出
        statusOptions: { // 有效无效下拉框
          '1': '有效',
          '0': '作废'
        },
        followOptions: { // 有效无效下拉框
          '1': '关注又注册',
          '0': '关注不注册'
        },

        dialogFormVisible: false, // 编辑框显示
        dialogStatus: '', // 编辑框更新插入状态
        textMap: { // 编辑框标题
          update: '编辑',
          create: '创建'
        },
        rules: { // 编辑框校验规则
          sxUserInfoName: [{ required: true, message: 'SX用户信息表名称', trigger: 'change' }]
        },
        pointListQuery: { // 表格查询对象
          pageNum: 1,
          pageSize: 10,
          userId: ''
        },
        pointListData: [],
        dialogPointFormVisible: false,
        pointListTotal: 0
      }
    },
    computed: {
      validSwitch: {
        // getter
        get: function() {
          return this.temp.validFlag === '1'
        },
        // setter
        set: function(newValue) {
          if (newValue) {
            this.temp.validFlag = '1'
          } else {
            this.temp.validFlag = '0'
          }
        }
      }
    },
    created() {
      this.fetchData()
    },
    methods: {

      /**
       * 导出用户二维码按钮
       */
      downQrUrl(row) {
        let that = this;
        let nickName = row.nickName + '分享二维码';
        this.$http.all([SxUserInfoApi.downQrUrl(row)])
          .then(this.$http.spread(function(perms) {
              let qrUrl = perms;
            that.downloadIamge(qrUrl , nickName);
          }))
      },

      downloadIamge(imgsrc, name) { // 下载图片地址和图片名
        let _sel = this;
        var image = new Image();
        // 解决跨域 Canvas 污染问题
        image.setAttribute("crossOrigin", "anonymous");
        if (imgsrc.indexOf('?') !== -1) {
          imgsrc += '&r=' + Math.random()
        } else {
          imgsrc += '?r=' + Math.random()
        }

        image.onload = function() {
          var canvas = document.createElement("canvas");
          canvas.width = image.width;
          canvas.height = image.height;
          var context = canvas.getContext("2d");
          context.drawImage(image, 0, 0, image.width, image.height);

          //得到图片的base64编码数据  "image/png"
          var url = canvas.toDataURL({format: 'png', multiplier: 4});
          // var strDataURI = url.substr(22, url.length);
          var blob = _sel.dataURLtoBlob(url);
          var objurl = URL.createObjectURL(blob);

          var a = document.createElement("a"); // 生成一个a元素
          var event = new MouseEvent("click"); // 创建一个单击事件
          a.download = name || "photo"; // 设置图片名称
          a.href = objurl; // 将生成的URL设置为a.href属性
          a.dispatchEvent(event); // 触发a的单击事件
        };
        image.src = imgsrc;
      },

      /**
       * 图片过大转换
       */
      dataURLtoBlob(dataurl) {
        var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while(n--){
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], {type:mime});
      },

      showPoint(row) {
        this.pointListQuery.userId = row.userId
        this.getUserPoint()
        this.dialogPointFormVisible = true
      },
      getUserPoint() {
        SxUserScoreRecordApi.getPage(this.pointListQuery).then(data => {
          this.pointListData = data.rows
          this.pointListTotal = data.total
        })
      },

      /**
       * 导出用户信息按钮
       */
      exportReport() {

        // 创建一个 form
         var form1 = document.createElement("form");
        form1.id = "form1";
        form1.name = "form1";

        // 添加到 body 中
        document.body.appendChild(form1);

        // 创建一个输入
        var input = document.createElement("input");
        // 设置相应参数
        input.type = "text";
        input.name = "query";
        input.value = this.listQuery.query;

        // 创建一个输入
        var input1 = document.createElement("input");
        // 设置相应参数
        input1.type = "text";
        input1.name = "times";
        if (this.buyTime && this.buyTime.length > 0) {
          input1.value = JSON.stringify(this.buyTime);
        } else {
          input1.value = null;
        }

        // 创建一个输入
        var input2 = document.createElement("input");
        // 设置相应参数
        input2.type = "text";
        input2.name = "userTel";
        input2.value = this.listQuery.userTel;

        // 将该输入框插入到 form 中
        form1.appendChild(input);
        form1.appendChild(input1);
        form1.appendChild(input2);

        // form 的提交方式
        form1.method = "POST";
        // form 提交路径
        form1.action = this.exportUrl;

        // 对该 form 执行提交
        form1.submit();
        // 删除该 form
        document.body.removeChild(form1);

      },

      /**
       * 获取表格数据
       */
      fetchData() {
        const that = this
        this.listLoading = true
        if (this.buyTime && this.buyTime.length > 0) {
          this.listQuery.times = JSON.stringify(this.buyTime);
        } else {
          this.listQuery.times = null;
        }
        this.$http.all([SxUserInfoApi.getPage(this.listQuery)])
          .then(this.$http.spread(function(perms) {
            that.list = perms.rows
            that.total = perms.total
            that.listLoading = false
          }))
      },
      /**
       * 新增弹窗
       */
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      /**
       * 清空弹窗内容
       */
      resetTemp() {
        this.temp = {
          userId: '',
          minOpenId: '',
          openId: '',
          unionId: '',
          nickName: '',
          headImg: '',
          userRankId: '',
          userRankName: '',
          userPoints: '',
          userLevel: '',
          userTel: '',
          payNo: '',
          moneyBalance: '',
          followFlag: '',
          followTime: '',
          createdTime: '',
          modifiedTime: '',
          lastLoginTime: '',
          userPw: '',
          userName: '',
          userSex: '',
          birthDay: '',
          defaultCard: '',
          validFlag: '1'
        }
      },
      /**
       * 确定新增
       */
      createData() {
        const that = this
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            SxUserInfoApi.insert(this.temp).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 1000,
                onClose() {
                  that.fetchData()
                }
              })
            })
          }
        })
      },
      /**
       * 编辑弹窗
       */
      handleUpdate(row) {
        this.temp = Object.assign({}, row)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      /**
       * 确认编辑
       */
      updateData() {
        const that = this
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            SxUserInfoApi.update(tempData).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 1000,
                onClose() {
                  that.fetchData()
                }
              })
            })
          }
        })
      },
      /**
       * 删除操作
       */
      handleDelete(row) {
        const that = this
        SxUserInfoApi.remove({ userId: row.userId }).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 1000,
            onClose() {
              that.fetchData()
            }
          })
        })
      },
      /**
       * 搜索过滤
       */
      handleFilter() {
        this.listQuery.pageNum = 1
        this.fetchData()
      }
    }
  }
</script>
